package org.dreamwork.smart.car.server.io;

import org.apache.log4j.Logger;
import org.dreamwork.smart.car.server.util.Config;

import java.io.IOException;
import java.net.*;

/**
 * Created with IntelliJ IDEA.
 * User: seth.yang
 * Date: 15-2-27
 * Time: 下午2:01
 */
public class BroadcastService implements Runnable {
    private boolean running = true;
    private static final Logger logger = Logger.getLogger (BroadcastService.class);

    private int udpPort;

    public BroadcastService (int udpPort) {
        this.udpPort = udpPort;
    }

    public void bind () throws IOException {
        new Thread (this).start ();
    }

    public synchronized void shutdown () {
        running = false;
    }

    @Override
    public void run () {
        try {
            DatagramSocket server = new DatagramSocket (udpPort);
            logger.info ("--------------------------------------------");
            logger.info (" Server listen on " + server.getLocalAddress () + ":" + udpPort);
            logger.info ("--------------------------------------------");
            int MAX_LENGTH = 16;
            while (running) {
                DatagramPacket packet = new DatagramPacket (new byte[MAX_LENGTH], MAX_LENGTH);
                if (logger.isDebugEnabled ())
                    logger.debug ("waiting for message ... ");
                server.receive (packet);
                if (logger.isDebugEnabled ())
                    logger.debug ("get a message !");

                int offset = packet.getOffset (), length = packet.getLength ();
                byte[] buff = packet.getData ();
                String hello = new String (buff, offset, length, "utf-8");
                if ("controller".equals (hello)) {
                    // we got a valid request

                    Config config = Config.getInstance ();
                    int controlPort = config.getIntValue (Config.CAR_REMOTE_PORT, -1);
                    int cameraPort = config.getIntValue (Config.CAMERA_PORT, -1);

                    buff = new byte[8];
                    byte[] p = int2Bytes (controlPort);
                    System.arraycopy (p, 0, buff, 0, 4);
                    p = int2Bytes (cameraPort);
                    System.arraycopy (p, 0, buff, 4, 4);

                    packet = new DatagramPacket (buff, buff.length, packet.getAddress (), packet.getPort ());
                    DatagramSocket socket = new DatagramSocket ();
                    socket.send (packet);
                }

                synchronized (this) {
                    if (!running)
                        break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace ();
        }
    }

    private static byte[] int2Bytes (int value) {
        byte[] buff = new byte[4];
        buff [0] = (byte) ((value >> 24) & 0xff);
        buff [1] = (byte) ((value >> 16) & 0xff);
        buff [2] = (byte) ((value >>  8) & 0xff);
        buff [3] = (byte) (value & 0xff);
        return buff;
    }
}
